<%@page language="java" isELIgnored="false" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<jsp:directive.include file="/WEB-INF/sitemesh-decorators/include.jsp" />
<c:set var="menu" value="user" scope="request" />

<html>
<head>
<title>Users</title>
<script type="text/javascript">
   $(document).ready(function () {
      $("#searchButton").jqxButton({ theme: getSowTheme('ui-redmond') });
      
      var source = {
         datatype: "json",
         datafields: [
			{ name: 'id' },
            { name: 'name' },
            { name: 'username' },
            { name: 'email' },
            { name: 'phone' },
            { name: 'role' },
            { name: 'enabled' }
         ],
         id: 'id',
         url: "<c:url value='/admin/user/search' />",
         async: false
      };

      var dataAdapter = new $.jqx.dataAdapter(source);
      var renderer = function (row, column, value, html) {
         return '<a href="user/' + dataAdapter.records[row].id + '">' + html + '</a>';
      };

      $("#userGrid").jqxGrid(
      {
         width: 870,
         source: dataAdapter,
         theme: getTheme(),
         columnsresize: true,
         pageable: true,
         autoheight: true,
         sortable: true,
         altrows: true,
         columns: [
            { text: 'Name', datafield: 'name', width: 180, cellsrenderer: renderer },
            { text: 'Username', datafield: 'username', width: 150 },
            { text: 'Email', datafield: 'email', width: 190 },
            { text: 'Phone', datafield: 'phone', width: 120 },
            { text: 'Role', datafield: 'role', minwidth: 140 },
            { text: 'Enabled', datafield: 'enabled', width: 90, columntype: 'checkbox' }
         ]
      });

      $("#searchButton").click(function () {
         var firstName = $("input[name='first']").val();
         var lastName = $("input[name='last']").val();
         var username = $("input[name='user']").val();
         var group = $("#jqxGroup").jqxComboBox("getSelectedItem").value;
         source.url = "<c:url value='/admin/user/search' />?firstName=" + firstName + "&lastName=" + lastName + "&username=" + username + "&group=" + group;
         dataAdapter.dataBind();
      });
   });

   function openDiaglog(title) {
      $("#userDialog").dialog({
         title: title,
         resizable: false,
         draggable: false,
         modal: true,
         width: 600,
         buttons: {
            "Save": function() {
               saveUser();
   			},
   			"Clear": function() {
   			   clearForm();
   			},
   			Cancel: function() {
   				$(this).dialog("close");
   			}
         }
      });
   }
   
   function openDeleteDiaglog() {
      var selectedIndex = $("#userGrid").jqxGrid('getselectedrowindex');
      if(selectedIndex < 0) {
         alert("Please select a row.");
         return;
      }

      $("#dialog-confirm").dialog({
         resizable: false,
         draggable: false,
         modal: true,
         width: 300,
         buttons: {
            "Delete all items": function() {
               deleteUser();
   			},
   			Cancel: function() {
   				$(this).dialog("close");
   			}
         }
      });
   }

   function closeDiaglog() {
      $('#userDialog').dialog('close');
   }

   function addUser() {
      $("#userDialog").load("<c:url value='/ajax/admin/user' />");
      openDiaglog("Add User");
   }

   function editUser() {
      var selectedIndex = $("#userGrid").jqxGrid('getselectedrowindex');
      if(selectedIndex < 0) {
         alert("Please select a row.");
         return;
      }

      var id = $("#userGrid").jqxGrid('getrowid', selectedIndex);
      $("#userDialog").load("<c:url value='/ajax/admin/user' />?id=" + id);
      openDiaglog("Edit User");
   }

   function saveUser() {
      $.ajax({
         url : "<c:url value='/ajax/admin/user/save' />",
         type : "POST",
         data: $('#userForm').serialize(),
         dataType : "html",
         success : function(data) {
            if($(data).first().attr("id") == "error") {
        	   $("#userDialog").html(data);
            } else {
                closeDiaglog();
                $("#userGrid").jqxGrid("source").dataBind();
            }
         }
      });
   }

   function clearForm() {
      $("input[name='username']").val("");
      $("input[name='password']").val("");
      $("input[name='enabled']").attr('checked', false);
      $("input[name='firstName']").val("");
      $("input[name='lastName']").val("");
      $("input[name='middleName']").val("");
      $("input[name='email']").val("");
      $("input[name='phone']").val("");
      $('#jqxCheckBox').jqxCheckBox('uncheck');
   }

   function deleteUser() {
      $('#dialog-confirm').dialog('close');

      var selectedIndex = $("#userGrid").jqxGrid('getselectedrowindex');
      var id = $("#userGrid").jqxGrid('getrowid', selectedIndex);
      $.ajax({
         url : "<c:url value='/ajax/admin/user/delete' />",
         type : "POST",
         data : { id: id },
         dataType : "html",
         success : function(data) {
            if(data == "error") {
        	   alert('error!!');
        	   return;
            }

            $("#userGrid").jqxGrid("source").dataBind();
         },
         error : function(){
            alert('-1');
         }
      });
   }
</script>
</head>

<body>
   <div class="cubeTitleWrapper">
      <span class="cube_title">Users</span>
   </div>

   <div class="cube">
      <div>
         <div class="contentwrapper">
            <div class="contentcolumn">
               <div class="innertube">
                  <h2 class="userDefinedBg curved">Search</h2>
                  <div class="contentBlock">
                     <form name="searchForm">
                     <table style="border-spacing: 2px;">
                        <tr>
                           <td>First Name: </td><td><input type="text" name="first" size="25" class="text ui-widget-content ui-corner-all" style="height: 22px" /></td>
                           <td width="10">&nbsp;</td>
                           <td>Last Name: </td><td><input type="text" name="last" size="25" class="text ui-widget-content ui-corner-all" style="height: 22px" /></td>
                        </tr>
                        <tr>
                           <td>Username: </td><td><input type="text" name="user" size="25" class="text ui-widget-content ui-corner-all" style="height: 22px" /></td>
                           <td></td>
                           <td>Group: </td><td><div id='jqxGroup'></div><div id="groupSource" style="display: none;"><c:out value="${groups}" /></div></td>
                           <script type="text/javascript">
                              $("#jqxGroup").jqxComboBox({ source: jQuery.parseJSON($("#groupSource").text()), displayMember: "name", valueMember: "id", width: 153, height: 22, theme: getSowTheme('ui-redmond') });
                              $("#jqxGroup").jqxComboBox('insertAt', 'All', 0);
                              $("#jqxGroup").jqxComboBox('selectIndex', 0);
                           </script>
                           <td rowspan="2" width="10">&nbsp;</td>
                           <td rowspan="2"><input id="searchButton" type="button" value="Search" style="cursor: pointer;" /></td>
                        </tr>
                     </table>
                     </form>
                  </div>
                  <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>

                  <h2 class="userDefinedBg curved">Users</h2>
                  <div class="contentBlock">
                     <div id='userWidget'><div id="userGrid">No results found</div></div>
                  </div>
                  <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>
               </div>
            </div>
         </div>

         <div class="rightcolumn">
            <div class="innertube">
               <h2 class="userDefinedBg"><span class="right_end"><span class="start">Tools</span></span></h2>
               <div class="contentBlock">
                  <ul class="toolbox userDefinedColor">
                     <li class="userDefinedBg"><a class="add_link add-sow" href="javascript:addUser()">Add New User</a></li>
                     <li class="userDefinedBg"><a class="add_link edit" href="javascript:editUser()">Edit Selected User</a></li>
                     <li class="delete"><a class="add_link delete" href="javascript:openDeleteDiaglog()">Delete Selected User(s)</a></li>
                  </ul>
               </div>
               <div class="contentBlock_bottom"><span class="right_end"><span></span></span></div>
            </div>
         </div>
      </div>
   </div>
   
   <div id="userDialog" style="display: none;"></div>
   <div id="dialog-confirm" title="Delete selected user(s)?" style="display: none;">
      <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>These users will be permanently deleted and cannot be recovered. Are you sure?</p>
   </div>
</body>
</html>